package com.yazi.mxz.mobile.controller.user;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;




import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.myframework.smhj.common.exception.MyException;
import com.myframework.smhj.hibernate.Page;
import com.myframework.smhj.hibernate.Searching;
import com.myframework.smhj.hibernate.Sort;
import com.myframework.smhj.jackson.result.ObjectResult;
import com.myframework.smhj.jackson.result.StatusResult;
import com.yazi.mxz.common.entity.beans.Address;
import com.yazi.mxz.common.entity.beans.Category;
import com.yazi.mxz.common.entity.beans.Order;
import com.yazi.mxz.common.entity.beans.ShoppingCart;
import com.yazi.mxz.common.entity.custom.Order4Search;
import com.yazi.mxz.common.entity.custom.Orders4Form;
import com.yazi.mxz.common.entity.custom.ShoppingCarts4Order;
import com.yazi.mxz.common.entity.enums.CategoryType;
import com.yazi.mxz.common.entity.enums.OrderStatus;
import com.yazi.mxz.common.service.CategoryService;
import com.yazi.mxz.common.service.OrderService;
import com.yazi.mxz.common.service.ShoppingCartService;

@Controller("user-orderController")
@RequestMapping("/user/order")
public class OrderController extends BaseController {
	private static Logger log = LoggerFactory.getLogger(OrderController.class);

	@Resource
	OrderService orderService;
	@Resource
	ShoppingCartService shoppingCartService;
	@Resource
	CategoryService categoryService;

	@RequestMapping("/list")
	public String list(Order4Search order4s, Searching si, Model model) {
		log.debug("进入个人订单列表页面");

		order4s.setMemberByMemberId(getMember());
		order4s.setIsMemberDel(false);

		// 默认按订单时间倒序
		if (null == si.getSorts()) {
			List<Sort> sorts = new ArrayList<Sort>();
			sorts.add(new Sort("orderTime", true));
			si.setSorts(sorts);
		}

		Page<Order> page;
		try {
			page = orderService.list(order4s, si);

		} catch (Exception e) {
			log.error("进入个人订单列表页面：", e);
			return FORWARD_TIP;
		}

		OrderStatus[] orderStatuses = OrderStatus.values();

		model.addAttribute("orderList", page.getList());
		model.addAttribute("orderStatuses", orderStatuses);
		return "user/order_list";
	}
	
	@RequestMapping("/page")
	public String page(Order4Search order4s, Searching si, Model model) {
		log.debug("获取个人订单分页列表");

		order4s.setMemberByMemberId(getMember());
		order4s.setIsMemberDel(false);

		// 默认按订单时间倒序
		if (null == si.getSorts()) {
			List<Sort> sorts = new ArrayList<Sort>();
			sorts.add(new Sort("orderTime", true));
			si.setSorts(sorts);
		}
		int destPage = si.getNowPage();
		Page<Order> page;
		try {
			page = orderService.list(order4s, si);
			// 当目标页与实际所得页不一致（老是最后一页）时，表示已经没有下一页了
			if (destPage != page.getPaging().getNowPage()) {
				page.getList().clear();
			}
			
		} catch (Exception e) {
			log.error("获取个人订单分页列表异常：", e);
			model.addAttribute(TIP_MSG, "加载失败");
			return FORWARD_TIP;
		}

		OrderStatus[] orderStatuses = OrderStatus.values();

		model.addAttribute("orderList", page.getList());
		model.addAttribute("orderStatuses", orderStatuses);
		return "user/order_list_page";
	}

	@RequestMapping("/add")
	public String add(ShoppingCarts4Order carts4s, Model model) {
		log.debug("进入订单添加页面");
		// 购物车商品
		List<ShoppingCart> cartList;
		// 用户默认收货地址
		Address defAddress;
		// 支付方式
		List<Category> payList;
		// 配送方式
		List<Category> deliveryList;
		try {

			cartList = shoppingCartService.checkForOrderByMember(getMember(),
					carts4s.getShoppingCarts());
			defAddress = getMember().getAddress();

			Category cat4s = new Category();// category for search
			cat4s.setDeep(1);
			// 支付方式
			cat4s.setType(CategoryType.PAY_TYPE.ordinal());
			payList = categoryService.list(cat4s);
			// 配送方式
			cat4s.setType(CategoryType.DELIVERY_METHOD.ordinal());
			deliveryList = categoryService.list(cat4s);

		} catch (MyException e) {
			log.debug("进入订单结算页面失败：{}", e.getMessage());
			model.addAttribute(TIP_DATA, e);
			return FORWARD_TIP;
		} catch (Exception e) {
			log.error("进入订单结算页面异常：", e);
			return FORWARD_TIP;
		}

		model.addAttribute("cartList", cartList);
		model.addAttribute("address", defAddress);
		model.addAttribute("pay", payList);
		model.addAttribute("delivery", deliveryList);
		return "user/order_add";
	}

	@RequestMapping("/addDo")
	public String addDo(Orders4Form ordersObj, Model model) {
		log.debug("提交订单");
		try {

			orderService.addByMember(getMember(), ordersObj);

		} catch (MyException e) {
			log.debug("订单提交失败：{}", e.getMessage());
			model.addAttribute(TIP_DATA, e);
			return FORWARD_TIP;
		} catch (Exception e) {
			log.error("订单提交异常：", e);
			return FORWARD_TIP;
		}
		return "user/order_addDo";
	}

	@RequestMapping("/statusDo/json")
	@ResponseBody
	public ObjectResult<?> statusDoJson(String orderCode, OrderStatus status) {
		log.debug("修改订单状态");
		ObjectResult<OrderStatus> jsonResult = new ObjectResult<OrderStatus>();
		try {
			status = orderService.editStatusByMemberId(getMemberId(), orderCode,
					status);
			if (null == status) {
				jsonResult.setFailMessage("操作失败");
			} else {
				jsonResult.setResult(status);
				jsonResult.setOkMessage("操作成功");
			}
		} catch (Exception e) {
			log.error("修改订单状态异常：", e);
			jsonResult.setErrorMessage("操作失败，请联系管理员。");
		}
		
		return jsonResult;
	}

	@RequestMapping("/delDo/json")
	@ResponseBody
	public StatusResult delDoJson(String orderCode) {
		log.debug("删除订单");
		StatusResult jsonResult = new StatusResult();
		try {
			if (orderService.removeByMemberId(getMemberId(), orderCode)) {
				jsonResult.setOkMessage("删除成功");
			} else {
				jsonResult.setFailMessage("删除失败");
			}
		} catch (Exception e) {
			log.error("删除订单异常：", e);
			jsonResult.setErrorMessage("操作失败，请联系管理员。");
		}
		return jsonResult;
	}

	@RequestMapping("/count/json")
	@ResponseBody
	public ObjectResult<Integer> count() {
		log.debug("获取未完成订单数量");
		ObjectResult<Integer> jsonResult = new ObjectResult<Integer>();
		// 待确认订单
		Integer[] statuses = new Integer[] { OrderStatus.DISPATCHING.ordinal(),
				OrderStatus.RECEIVE.ordinal() };
		Order4Search order = new Order4Search();

		try {

			order.setMemberByMemberId(getMember());
			order.setIsMemberDel(false);
			order.setStatuses(statuses);

			jsonResult.setResult(orderService.count(order, null));
			jsonResult.setOk();
		} catch (Exception e) {
			log.error("获取未完成订单数量异常：", e);
			jsonResult.setErrorMessage("获取订单数量失败");
		}
		return jsonResult;
	}

	@RequestMapping("/detail/{orderCode}")
	public String detail(@PathVariable String orderCode, Model model) {
		log.debug("detail:进入订单详情页面");
		Order order = new Order();
		try {
			order.setMemberByMemberId(getMember());
			order.setOrderCode(orderCode);
			List<Order> orderList = orderService.list(order);
			if (orderList.size() != 1) {
				model.addAttribute(TIP_MSG, "订单信息不存在");
				return FORWARD_TIP;
			}
			order = orderList.get(0);

		} catch (Exception e) {
			log.error("进入订单详情页面异常：", e);
			return FORWARD_TIP;
		}

		// 订单状态
		OrderStatus[] orderStatuses = OrderStatus.values();

		model.addAttribute("order", order);
		model.addAttribute("statuses", orderStatuses);
		return "user/order_detail";
	}
	
	@RequestMapping("/detail")
	public String detailBySerialCode(String serialCode, Model model) {
		log.debug("detailBySerialCode:进入订单详情页面");
		Order order = new Order();
		try {
			order.setMemberByMemberId(getMember());
			order.setSerialCode(serialCode);
			List<Order> orderList = orderService.list(order);
			if (orderList.size() != 1) {
				model.addAttribute(TIP_MSG, "订单信息不存在");
				return FORWARD_TIP;
			}
			order = orderList.get(0);

		} catch (Exception e) {
			log.error("进入订单详情页面异常：", e);
			return FORWARD_TIP;
		}

		// 订单状态
		OrderStatus[] orderStatuses = OrderStatus.values();

		model.addAttribute("order", order);
		model.addAttribute("statuses", orderStatuses);
		return "user/order_detail";
	}
	
	@RequestMapping("/listStatus/json")
	@ResponseBody
	public ObjectResult<?> listStatusJson() {
		log.debug("获取订单状态枚举列表");
		ObjectResult<OrderStatus[]> jsonResult = new ObjectResult<OrderStatus[]>();
		jsonResult.setResult(OrderStatus.values());
		jsonResult.setOk();
		return jsonResult;
	}
	
}
